package com.weiaibenpao.demo.chislim.utils;

import android.graphics.Bitmap;
import android.util.Log;
import android.view.View;

/**
 * Created by wlx on 2017/12/15.
 */

public class LoadBitmapFromView {
        public static Bitmap getViewToBitmap(View v){
//            if (view == null) {
//                return null;
//            }
//            Bitmap screenshot;
//            screenshot = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
//            Canvas c = new Canvas(screenshot);
//            view.draw(c);
//            return screenshot;
            boolean willNotCache = v.willNotCacheDrawing();
            v.setWillNotCacheDrawing(false);
            // Reset the drawing cache background color to fully transparent
            // for the duration of this operation
            int color = v.getDrawingCacheBackgroundColor();
            v.setDrawingCacheBackgroundColor(0);
            if (color != 0) {
                v.destroyDrawingCache();//若想更新cache, 必须要调用destroyDrawingCache方法把旧的cache销毁，才能建立新的。
            }
            v.buildDrawingCache();//If you call buildDrawingCache() manually without calling setDrawingCacheEnabled(true), you should cleanup the cache by calling destroyDrawingCache() afterwards.
            Bitmap cacheBitmap = v.getDrawingCache();
            if (cacheBitmap == null) {
                Log.e("getViewBitmap", "failed getViewBitmap(" + v + ")", new RuntimeException());
                return null;
            }
            Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);//创建一个DrawingCache的拷贝，因为DrawingCache得到的位图在禁用后会被回收
            // Restore the view
            v.destroyDrawingCache();
            v.setWillNotCacheDrawing(willNotCache);
            v.setDrawingCacheBackgroundColor(color);
            return bitmap;
        }
}
